<template>
  <div>
    <button @click="startRecording" :disabled="isRecording">开始录音</button>
    <button @click="stopRecording" :disabled="!isRecording">停止录音</button>
    <audio ref="audioPlayer" controls></audio>
  </div>
</template>

<script setup>
import { ref } from 'vue'

// 存储录音数据的数组
const recordedChunks = ref([])
// 媒体录制器实例
const mediaRecorder = ref(null)
// 音频播放器引用
const audioPlayer = ref(null)
// 录音状态
const isRecording = ref(false)

// 开始录音
const startRecording = async () => {
  try {
    // 请求用户媒体权限
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
    // 创建 MediaRecorder 实例
    mediaRecorder.value = new MediaRecorder(stream)

    // 监听数据可用事件
    mediaRecorder.value.ondataavailable = (event) => {
      if (event.data.size > 0) {
        recordedChunks.value.push(event.data)
      }
    }

    // 监听录音停止事件
    mediaRecorder.value.onstop = () => {
      // 创建音频 Blob 对象
      const audioBlob = new Blob(recordedChunks.value, { type: 'audio/webm' })
      // 创建音频 URL
      const audioUrl = URL.createObjectURL(audioBlob)
      // 设置音频播放器的源
      audioPlayer.value.src = audioUrl
      // 清空录音数据数组
      recordedChunks.value = []
      isRecording.value = false
    }

    // 开始录音
    mediaRecorder.value.start()
    isRecording.value = true
  } catch (error) {
    console.error('录音出错:', error)
  }
}

// 停止录音
const stopRecording = () => {
  if (mediaRecorder.value && mediaRecorder.value.state === 'recording') {
    mediaRecorder.value.stop()
  }
}
</script>
